package demo2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

//tcp客户端
public class TcpEchoClient {
    private Socket socket = null;
    public TcpEchoClient(String ip,int port) throws IOException {
        socket = new Socket(ip,port);
    }
    public void start() {
        System.out.println("客户端启动！");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            Scanner scanner = new Scanner(System.in);
            Scanner scannerNext = new Scanner(inputStream);
            while (true) {
                //1.输入请求
                System.out.print("请输入你的请求：");
                String request = scanner.next();
                request += "\n";
                //2.发送请求
                outputStream.write(request.getBytes());
                //3.接收响应
                if(!scannerNext.hasNext()) {
                    break;
                }
                String response = scannerNext.next();
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1",1314);
        tcpEchoClient.start();
    }

}
